<?php
require_once 'BaseController.php';

/**
 * 【SP版】さがしてべあ～君 コントローラ
 */
class Mobileapi_RequestSearchController extends Mobileapi_BaseController
{

    /**
     * メインアクション
     */
    public function indexAction()
    {
        unset($_SESSION['_SESSION_ID']);

        $params = $this->getParameters();

        // URLが初期状態・完了でない場合はリダイレクト
        if ($params['Method'] != 'complete' && $params['Method'] != '')
        {
            header("Location: /sp/search/requestsearch/");
            exit();
        }

        // 表示テンプレートパス設定
        if ($params['Method'] == 'complete')
        {
            $sess_vals = $_SESSION['_REQUESTSEARCH_PARAMS'];
            if (empty($sess_vals))
            {
                header("Location: /sp/search/requestsearch/");
                exit();
            }

            if (is_array($sess_vals))
            {
                foreach ($sess_vals as $key => $val)
                {
                    $params[$key] = $val;
                }
            }

            unset($_SESSION['_REQUESTSEARCH_PARAMS']);

            $this->_data['hiddenTag'] = Apm_Util::generateHiddenTag($params, array());

            // ★★★周辺物件探す

            $shuuhens = array();
            $jouken = array();

            $jouken['take'] = 5;

            $armodel = new Rstdtl_Model_Articledtl();

            if ($params['area'] == "0")
            {
                $jouken['T03_TODOUFUKEN_CD'] = $params['PrefCd'];
                $jouken['T03_SHIKUCHOUSON_CD'] = substr($params['CityCd'], 2, 3);
                $shuuhenBukken = $armodel->getShuuhenBukken($jouken);
            }
            else
            {

                $jouken['PrefCd'] = $params['PrefCd'];
                $jouken['StCd'] = array();

                if (!empty($params['StCd1'])) $jouken['StCd'][] = $params['StCd1'];
                if (!empty($params['StCd2'])) $jouken['StCd'][] = $params['StCd2'];
                if (!empty($params['StCd3'])) $jouken['StCd'][] = $params['StCd3'];

                $shuuhenBukken = $armodel->getShuuhenBukkenForLine($jouken);
            }

            foreach ($shuuhenBukken as $d)
            {
                $d['T03_YACHIN_STR'] = Apm_Bukkenitems::GetChinryouStr($d);
                $d['T03_KANRI_KYOEKI_STR'] = Apm_Bukkenitems::GetKyouekihiStr($d, 0);
                $d['T03_SHIKIKIN_STR'] = Apm_Bukkenitems::GetShikikinStr($d); // 敷金
                $d['T03_REIKIN_STR'] = Apm_Bukkenitems::GetReikinStr($d);
                $d['T03_MADORI_STR'] = Apm_Bukkenitems::GetMadoriStr($d); // 間取り
                $d['T03_SENYUU_MENSEKI_STR'] = Apm_Bukkenitems::GetSenyuuMensekiStr($d);
                // 部屋向き
                $list[$i]['CONVERT_T03_HOUGAKU'] = Apm_Bukkenitems::GetHeyamukiStr($d);

                // 内装
                $OemFlg = true;
                $nasouGazou = Apm_Bukkenitems::GetImageData($d, Apm_Config_Search::IMG_TYPE_NAISO, $OemFlg);

                if (count($nasouGazou) == 0)
                {
                    $OemFlg = false;
                    $nasouGazou = Apm_Bukkenitems::GetImageData($d, Apm_Config_Search::IMG_TYPE_NAISO, $OemFlg);
                }
                $d['BUKEN_IMAGE'][Apm_Config_Search::IMG_TYPE_NAISO] = $nasouGazou;

                if (count($nasouGazou) == 0)
                {
                    // 概観
                    $OemFlg = true;
                    $gaikanGazou = Apm_Bukkenitems::GetImageData($d, Apm_Config_Search::IMG_TYPE_GAIKAN, $OemFlg);

                    if (count($gaikanGazou) == 0)
                    {
                        $OemFlg = false;
                        $gaikanGazou = Apm_Bukkenitems::GetImageData($d, Apm_Config_Search::IMG_TYPE_GAIKAN, $OemFlg);
                    }
                    $d['BUKEN_IMAGE'][Apm_Config_Search::IMG_TYPE_GAIKAN] = $gaikanGazou;
                }

                $d["CONVERT_T03_YACHIN"] = Apm_Bukkenitems::GetChinryouStr($d);
                $shuuhens[] = $d;
            }

            $this->_data['shuuhen'] = $shuuhens;
            // ★★★周辺物件探す

            $this->displayBody2('complete');
            exit();
        }

        session_start();

        $_SESSION['_SESSION_ID'] = uniqid();
        // hiddenフィルドにセックションを格納
        $params['session_id'] = $_SESSION['_SESSION_ID'];

        // 表示テンプレートパス設定
        $this->displayConditions($params);
    }

    public function checkSession($params)
    {
        if ($_SESSION['_SESSION_ID'] != $params['session_id'])
        {
            header("Location: /sp/search/requestsearch/");
            exit();
        }
    }

    public function postCampaignValues($params)
    {
        // 20150117 S_Add
        $p_campaigns = $this->collectCampaignFromParams($params);
        $this->_data['p_campaigns'] = $p_campaigns;

        $model_cam = new Mobileapi_Model_BukkenCampaign();
        $temp = $model_cam->getNormalCampaigns(); // キャンペーンデータ取得

        $keys = array();
        $campaigns = array();

        foreach ($temp as $k => $cam)
        {
            $cam['name'] = 'campaign' . $k;

            if (in_array($cam['M94_CAMPAIGN_CD'], $p_campaigns))
            {
                $cam['checked'] = ' checked';
            }

            $keys[] = $cam['name'];
            $campaigns[] = $cam;
        }
        $this->_data['CAMPAIGNS'] = $campaigns;
        // 20150117 E_Add

        return $keys;
    }

    /**
     * メインアクション(post)
     */
    public function postAction()
    {
        $params = $this->getParameters();
        $this->_data = $params;

        if ($params['Method'] == '')
        {
            // 表示テンプレートパス設定
            $this->displayIndex($params);
        }
        else if ($params['Method'] == 'conditions')
        {
            // 表示テンプレートパス設定
            $this->displayConditions($params);
        }
        else if ($params['Method'] == 'shop')
        {
            // 表示テンプレートパス設定
            $this->displayShop($params);
        }
        // =>内容確認処理
        else if ($params['Method'] == 'confirm')
        {
            $this->checkSession($params);

            $excludes = array();
            $this->_data['hiddenTag'] = Apm_Util::generateHiddenTag($params, $excludes);

            $shopNameDisplay = "";
            foreach ($params as $key => $value)
            {
                if (strncmp($key, "shopdetail_", 11) == 0)
                {
                    $shopNameDisplay .= "" . $value . "<br/>";
                }
            }
            $this->_data['shopNameDisplay'] = $shopNameDisplay;
            $this->postCampaignValues($params);

            // 表示テンプレートパス設定
            $this->displayBody2('confirm');
        }
        else if ($params['Method'] == 'city')
        {
            $html = $this->selCity($params);
            // 返還
            Apm_Util::outputXPassThroutgh();
            echo $html;
            exit();
        }
        else if ($params['Method'] == 'ensen')
        {
            $html = $this->selEnsen($params);

            // 返還
            Apm_Util::outputXPassThroutgh();
            echo $html;
            exit();
        }

        else if ($params['Method'] == 'eki')
        {
            $this->loadEki($params);
            $html = $this->selEki('request_eki');

            // 返還
            Apm_Util::outputXPassThroutgh();
            echo $html;
            exit();
        }
    }

    /**
     * 市区町村検索
     */
    public function selCity($params)
    {
        // 都道府県CDが存在するか
        if (!empty($params['PrefCd']))
        {

            if (!is_array($params['PrefCd'])) $params['PrefCd'] = array(
                $params['PrefCd']
            );

            // 市区町村検索
            $model = new Search_Model_Selsikucyoson();
            $this->_data['cityData'] = $model->getRequestShikucyosonData($params);
        }
        else
        {
            $this->_data['cityData'] = null;
        }
        $helper = $this->getApmHelper('request_city');
        return $helper->getBlock($this->_data);
    }

    /**
     * 沿線検索
     */
    public function selEnsen($params)
    {
        // 都道府県CDが存在するか
        if (!empty($params['PrefCd']))
        {

            if (!is_array($params['PrefCd'])) $params['PrefCd'] = array(
                $params['PrefCd']
            );

            // 沿線検索
            $model = new Search_Model_Selensen();
            $this->_data['ensenData'] = $model->getRequestEnsenDataByMulti($params);
        }
        else
        {
            $this->_data['ensenData'] = null;
        }
        $helper = $this->getApmHelper('request_ensen');
        return $helper->getBlock($this->_data);
    }

    /**
     * 沿線検索
     */
    public function selEki($template)
    {
        $helper = $this->getApmHelper($template);
        return $helper->getBlock($this->_data);
    }

    public function loadEki($params)
    {
        // 都道府県CDが存在するか
        if (!empty($params['RailCd']))
        {
            if (!is_array($params['PrefCd'])) $params['PrefCd'] = array(
                $params['PrefCd']
            );

            if (!is_array($params['RailCd'])) $params['RailCd'] = array(
                $params['RailCd']
            );

            // 沿線検索
            $model = new Search_Model_Seleki();
            $this->_data['ekiData'] = $model->getRequestEkiData($params);
        }
        else
        {
            $this->_data['ekiData'] = null;
        }
    }

    /**
     * 条件選択画面表示
     *
     * @param $params リクエストパラメータ
     */
    private function displayConditions($params)
    {
        $this->checkSession($params);
        $this->selCity($params);

        // メインブロック生成
        $this->_data['main_block'] = $this->selCity($params);
        $this->_data['ensen_block'] = $this->selEnsen($params);

        $this->loadEki($params);
        $this->_data['eki_block1'] = $this->selEki('request_eki');
        $this->_data['eki_block2'] = $this->selEki('request_eki2');
        $this->_data['eki_block3'] = $this->selEki('request_eki3');

        // hiddenタグに表示しない項目
        $excludes = array(
            'area',
            'PrefCd',
            'CityCd',
            'RailCd',
            'StCd1',
            'StCd2',
            'StCd3',
            'tinryo',
            'madori',
            'menseki',
            'ekitoho',
            'Comment',
            'hidAreaDisplay',
            'hidYachinDisplay',
            'hidMadoriDisplay',
            'hidMensekiDisplay',
            'hidEkitohoDisplay'
        );
        $this->_data['hiddenTag'] = Apm_Util::generateHiddenTag($params, $excludes);

        $this->displayBody2('conditions');
    }

    /**
     * 相談する店舗画面表示
     *
     * @param $params リクエストパラメータ
     */
    private function displayShop($params)
    {
        $this->checkSession($params);
        $params_tmp = array();

        $params_tmp['todoufukenCd'] = $this->_data['PrefCd'];
        if ($params["area"] == "0")
        {
            $params_tmp['shikuchosonCd'] = $this->_data['CityCd'];
        }
        else
        {
            $params_tmp['ekiCdList'] = array();

            if (!empty($this->_data['StCd1'])) $params_tmp['ekiCdList'][] = $this->_data['StCd1'];
            if (!empty($this->_data['StCd2'])) $params_tmp['ekiCdList'][] = $this->_data['StCd2'];
            if (!empty($this->_data['StCd3'])) $params_tmp['ekiCdList'][] = $this->_data['StCd3'];
        }

        $model = new Search_Model_Selareasearch();
        $shopData = $model->getSearchShopList2($params_tmp);

        // hiddenタグに表示しない項目
        $excludes = array(
            'selshopes'
        );
        $SelShopCd = array();

        foreach ($params as $key => $value)
        {
            if (strncmp($key, "shopdetail_", 11) == 0)
            {
                $shopcd = split("_", $key)[1];
                foreach ($shopData as $shop)
                {
                    if ($shop['M05_TENPO_CD'] == $shopcd)
                    {
                        $SelShopCd["$shopcd"] = 1;
                        break;
                    }
                }
                $excludes[] = "shopdetail_" . $shopcd;
            }
        }

        if (count($SelShopCd) == 0 && count($shopData) > 0)
        {
            $cnt = 1;
            foreach ($shopData as $shop)
            {
                $SelShopCd[$shop['M05_TENPO_CD']] = 1;
                if ($cnt == 6) break;
                $cnt++;
            }
        }

        $this->_data['hiddenTag'] = Apm_Util::generateHiddenTag($params, $excludes);

        $this->_data['SelShopCd'] = $SelShopCd;
        $this->_data['shopNameDisplay'] = $shopNameDisplay;

        $this->_data['shopData'] = $shopData;

        // 表示テンプレートパス設定
        $this->displayBody2('shop');
    }

    /**
     * お客様情報画面表示
     *
     * @param $params リクエストパラメータ
     */
    private function displayIndex($params)
    {
        $this->checkSession($params);

        // hiddenタグに表示しない項目
        $excludes = array(
            'NameSei',
            'NameMei',
            'NameSeiKana',
            'NameMeiKana',
            'Mail',
            'Tel'
        );

        $campaignKeys = $this->postCampaignValues($params);

        if ($params["input"] == '1')
        {
            // hiddenタグに表示しない項目
            foreach ($campaignKeys as $val)
            {
                $excludes[] = $val;
            }
        }
        else
        {
            // 入力画面に遷移したことがあるかどうかを判定するための情報
            // hiddenタグに表示するようにする
            $params["input"] = '1';

            $campaigns = array();

            // 初回のみキャンペーンを全てチェック
            foreach ($this->_data['CAMPAIGNS'] as $k => $cam)
            {
                $cam['checked'] = ' checked';
                $campaigns[] = $cam;
            }
            $this->_data['CAMPAIGNS'] = $campaigns;
        }

        $this->_data['hiddenTag'] = Apm_Util::generateHiddenTag($params, $excludes);

        // 表示テンプレートパス設定
        $this->displayBody2('index');
    }

}
?>